<?php

namespace app\admin\controller\subject;

//引入进来基类控制器
use app\common\controller\Backend;

/**
 * 课程管理控制器
 */
class Subject extends Backend{
    
    //设置关联查询
    protected $relationSearch = true;

    //当前模型
    protected $model = null;

    //当前无须登录方法
    protected $noNeedLogin = [];

    //无需鉴权的方法,但需要登录
    protected $noNeedRight = [];

    //构造函数
    public function __construct()
    {
        parent::__construct();

        //将控制器和模型关联
        $this->model = model('Subject.Subject');
        $this->CategoryModel = model('Subject.Category');
        $this->ChapterModel = model('Subject.Chapter');
        
    }
    
    public function index()
    {
        //接收请求，查询数据
        // 判断是否有ajax请求

        //将请求当中所有的参数去除html标签，去掉两边空白
        $this->request->filter(['strip_tags', 'trim']);

        if($this->request->isAjax())
        {
            //获取表格所提交过来筛选和排序的一些参数
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            //表格需要两个返回值参数 总条数，分页的数据
            $total = $this->model
                ->with(['category'])
                ->where($where)
                ->order($sort, $order)
                ->count(); //返回查询的总数
            
            //返回多条数据，是二维数组结构
            $list = $this->model
                ->with(['category'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            // 打印多条数据
            // var_dump(collection($list)->toArray());
            // exit;

            //打印sql语句
            // echo $this->model->getLastSql();
            // exit;

            //组装数据
            $result = ['total' => $total, 'rows' => $list];

            //返回json数据给ajax结果
            return json($result);
        }

        return $this->view->fetch();
    }

    public function add()
    {
        if($this->request->isPost())
        {
            //接收row前缀的数据，并接收为数组类型
            $params = $this->request->param('row/a');

            //组装数据
            $data = [
                'title' => $params['title'],
                'price' => $params['price'],
                'content' => $params['content'],
                'thumbs' => $params['thumbs'],
                'cateid' => $params['cateid'],
            ];
            
            //插入到数据库中
            $result = $this->model->validate('common/Subject/Subject')->save($data);

            if($result === FALSE)
            {
                $this->error($this->model->getError());
                exit;
            }else
            {
                $this->success('添加课程成功');
                exit;
            }

        }


        //先将课程分类查询出来
        $catelist = $this->CategoryModel->column('id,name');
        $this->assign('catelist', build_select('row[cateid]', $catelist, [], ['class'=>'selectpicker', 'required'=>'']));

        return $this->view->fetch();
    }

    public function edit($ids = NULL)
    {
        //根据id要判断数据是否存在
        $row = $this->model->find($ids);

        //数据丢失，记录不存在
        if(!$row)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        //判断是否有post过来请求
        if($this->request->isPost())
        {
            //接收row前缀请求参数，并返回一个数组类型
            $params = $this->request->param('row/a');

            //组装数据
            $data = [
                'id' => $ids,
                'title' => $params['title'],
                'content' => $params['content'],
                'price' => $params['price'],
                'cateid' => $params['cateid'],
                'thumbs' => $params['thumbs'],
            ];

            //直接去更新
            $result = $this->model->validate('common/Subject/Subject')->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error($this->model->getError());
                exit;
            }

            //判断是否有上传新图片 
            if($data['thumbs'] != $row['thumbs'])
            {
                //不相等就说明有换图片了，就删除掉旧图片
                is_file(".".$row['thumbs']) && @unlink(".".$row['thumbs']);
            }

            $this->success('编辑课程成功');
            exit;
        }



        //先将课程分类查询出来
        $catelist = $this->CategoryModel->column('id,name');
        $this->assign('catelist', build_select('row[cateid]', $catelist, $row['cateid'], ['class'=>'selectpicker', 'required'=>'']));

        // 有数据要赋值到模板中去
        $this->assign('row', $row);

        //模板渲染
        return $this->view->fetch();
    }

    //软删除
    public function del($ids = NULL)
    {
        $list = $this->model->select($ids);
        
        //没有数据
        if(!$list)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        //软删除
        $result = $this->model->destroy($ids);

        if($result === FALSE)
        {
            $this->error('删除失败');
            exit;
        }else
        {
            $this->success('删除成功');
            exit;
        }
    }

    // --------------- 回收站 ---------------
    //恢复
    public function restore($ids = NULL)
    {
        //根据id判断数据是否存在
        $rows = $this->model->withTrashed()->whereIn('id', $ids)->select();

        if (!$rows) {
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->withTrashed()->whereIn('id', $ids)->update(['deletetime' => NULL]);

        if ($result === FALSE) {
            $this->error('恢复数据失败');
            exit;
        } else {
            $this->success('恢复数据成功');
            exit;
        }
    }

    //真实删除
    public function destroy($ids = NULL)
    {
        //根据id判断数据是否存在
        $rows = $this->model->withTrashed()->whereIn('id', $ids)->select();

        if (!$rows) {
            $this->error(__('No Results were found'));
            exit;
        }

        // 删除图片
        // 要从数据源中提取出thumbs这个字段的值
        $thumbs = array_column($rows, "thumbs");
        // 去重和去空
        $thumbs = array_filter($thumbs);
        $thumbs = array_unique($thumbs);
        // 真实删除 课程表中所有符合条件的记录
        $resultPhoto = $this->model->withTrashed()->whereIn('id', $ids)->delete(true);

        // 删除视频文件 (章节表)
        // 获取到当前课程下的所有章节信息
        // 重新指向model
        $this->model = $this->ChapterModel;
        $chapterList = $this->model->whereIn('subid', $ids)->select();
        //要从数据源中提取出url这个字段的值
        $videoUrl = array_column($chapterList, "url");
        //去重和去空
        $videoUrl = array_filter($videoUrl);
        $videoUrl = array_unique($videoUrl);
        // 真实删除 章节表中所有符合条件的记录
        $resultVideo = $this->model->whereIn('subid', $ids)->delete(true);

        if ($resultPhoto  === FALSE || $resultVideo  === FALSE) {
            $this->error('销毁失败');
            exit;
        } else {
            //删除图片文件
            if (!empty($thumbs)) {
                //循环遍历
                foreach ($thumbs as $item) {
                    //如果图片存在就删除掉
                    is_file("." . $item) && @unlink("." . $item);
                }
            }
            //删除视频文件
            if (!empty($videoUrl)) {
                //循环遍历
                foreach ($videoUrl as $item) {
                    //如果图片存在就删除掉
                    is_file("." . $item) && @unlink("." . $item);
                }
            }

            $this->success('销毁数据成功');
            exit;
        }
    }
}

